import { BrowserWindow, shell } from 'electron'
import { is } from '@electron-toolkit/utils'
import { join, } from 'path'
import BaseWindow from './components/BaseWindow'
import icon from '../../../resources/icon.png?asset'

export default class UserManagementWindow extends BaseWindow {
  //创建窗口
  create(): void {
    if (this.frame !== null && !this.frame.isDestroyed()) return
    this.frame = new BrowserWindow({
      width: 1000,
      height: 800,
      show: false,
      minWidth: 700,
      minHeight: 500,
      frame: true, // 无边框窗口
      autoHideMenuBar: true, // 隐藏菜单栏 默认值为false
      skipTaskbar: false, // 不显示在任务栏 默认值为false
      icon,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false, // 禁用沙箱模式
        zoomFactor: 1.0, // 禁止缩放
      }
    })

    this.frame.on('ready-to-show', () => {
      this.frame!.maximize() // 先最大化
      this.frame!.show()

      // 只在开发模式下开启 DevTools（嵌入在右侧）
      if (is.dev) {
        this.frame!.webContents.openDevTools({ mode: 'right' })

        // 支持 F12 切换 DevTools
        this.frame!.webContents.on('before-input-event', (_event, input) => {
          if (input.type === 'keyDown' && input.key === 'F12') {
            if (this.frame!.webContents.isDevToolsOpened()) {
              this.frame!.webContents.closeDevTools()
            } else {
              this.frame!.webContents.openDevTools({ mode: 'right' })
            }
          }
        })
      }
    })

    const routerPath = '/userManagement'
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath)
    } else {
      this.frame.loadFile(join(__dirname, '../renderer/index.html'), {
        hash: routerPath
      })
    }

    // 设置窗口打开链接的处理方式
    this.frame.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })
  }

}
